﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.IO;

namespace PriceCacheDownloader
{
    public static class Requestor
    {
        public static string DoRequest(string requestString, string serviceUrl, bool isBasicCode = false)
        {
            string responseXml = string.Empty;
            ServicePointManager.ServerCertificateValidationCallback =
                   new RemoteCertificateValidationCallback(CheckValidationResult);
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            webRequest.ProtocolVersion = HttpVersion.Version10;
            webRequest.Method = "POST";
            webRequest.KeepAlive = false;
            webRequest.ContentType = "text/xml;charset=UTF-8";
            webRequest.Timeout = 60000 ;
            webRequest.ReadWriteTimeout = 60000;
            if (isBasicCode)
            {
                string code = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "ctripltd", 9265)));
                //添加Authorization到HTTP头                
                webRequest.Headers.Add("Authorization", "Basic " + code);
            }
            byte[] requestByteArray = Encoding.UTF8.GetBytes((string)requestString);
            webRequest.ContentLength = requestByteArray.Length;
            using (Stream reqStream = webRequest.GetRequestStream())
            {
                reqStream.Write(requestByteArray, 0, requestByteArray.Length);
                reqStream.Close();
            }
            using (var response = webRequest.GetResponse())
            {
                using (Stream sr = response.GetResponseStream())
                {
                    responseXml = new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
                }
            }
            
            return responseXml;
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }
    }
}
